﻿Imports System.ComponentModel
Imports System.Drawing.Drawing2D
Imports System.Drawing
Imports System.Data.OleDb
Imports System.Deployment.Application

Public Class Form1

    Private WithEvents hookHandle As HookSel = New HookSel()
    Private ReadOnly ini_obj = New Rwini()
    Private conn As OleDbConnection
    Private app_path As String
    Private ini_file As String
    Private Const cGrip As Integer = 16
    Private Const cCaption As Integer = 32
    Public singleModel As Boolean = False
    Public stopHook As Boolean = False
    Private m2 = New Mini()

    Private Sub hookHandle_selComplete(ByVal hwnd As Integer, ByVal wps As Boolean) Handles hookHandle.selComplete
        Try
            Dim parentHwnd = hookHandle.findTopParent(hwnd)
            Dim my_pid, wai_pid As Integer
            If wps = False Then
                '向线程发送
                Try

                    my_pid = GetCurrentThreadId()
                    wai_pid = GetWindowThreadProcessId(parentHwnd, 0&)
                    If my_pid <> wai_pid Then
                        AttachThreadInput(my_pid, wai_pid, True)
                    End If
                    '保证获取到前台窗口
                    System.Threading.Thread.Sleep(300)
                    SetForegroundWindow(parentHwnd)
                    BringWindowToTop(hwnd)
                    hookHandle.NetSendKeyCTRLplus(67)
                Catch ex As Exception
                    SendKeys.Send("^(C）")
                End Try

            Else
                'wps需要全局
                System.Threading.Thread.Sleep(1000)
                SetForegroundWindow(parentHwnd)
                hookHandle.NetSendKeyCTRLplus(67)
            End If
            System.Threading.Thread.Sleep(500)
            Dim getSelT As String = Clipboard.GetText()
            If getSelT <> "" Then
                source_from.Text = getSelT
            End If
            If wps = False And my_pid <> wai_pid Then
                '解除附加
                AttachThreadInput(my_pid, wai_pid, False)
            End If
        Catch ex As Exception
            source_to.Text = ex.Message
        End Try
    End Sub

    Private Sub Form1_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
        hookHandle.UnHook()
        If conn.State = ConnectionState.Open Then
            conn.Close()
        End If
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        main_window = Me
        Try
            toptitle.Text = "追影划词翻译助手 V" & Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
        Catch ex As Exception
            toptitle.Text = "追影划词翻译助手 V1.0.0"
        End Try
        Me.Left = (My.Computer.Screen.Bounds.Size.Width - Me.Width) / 2
        Me.Top = (My.Computer.Screen.Bounds.Size.Height - Me.Height - 50)
        Try
            '数据库连接
            app_path = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)
            ini_file = app_path & "\app.ini"
            conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" & app_path & "\landata.mdb;")
            conn.Open()
            '初始化引擎列表
            Dim engine As New Generic.Dictionary(Of Integer, String)
            engine.Add(0, "百度")
            'engine.Add(1, "微软")
            engine.Add(2, "有道")
            select_engine.Items.Clear()
            Dim al As ArrayList = New ArrayList()
            For Each o As KeyValuePair(Of Integer, String) In engine
                al.Add(New TransEngine(o.Key, o.Value))
            Next
            select_engine.DataSource = al
            select_engine.DisplayMember = "engine_name"
            select_engine.ValueMember = "id"
            Dim ini_engine = ini_obj.GetINIW("setting", "engine", "0", ini_file)
            select_engine.SelectedValue = CInt(ini_engine)
            global_engine = CInt(ini_engine)
            bind_lan()
            selfHwnd = Me.Handle.ToInt32
            Dim path As GraphicsPath = GetRoundedRectPath(Me.ClientRectangle, 20)
            Me.Region = New Region(path)
            '开始hook
            hookHandle.StartHook()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub select_engine_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles select_engine.SelectionChangeCommitted
        global_engine = select_engine.SelectedValue
        bind_lan()
        ini_obj.WriteINIW("setting", "engine", select_engine.SelectedValue, ini_file)
    End Sub

    Private Sub bind_lan()
        Try
            Dim dt_from, dt_to As New DataTable
            '源语种
            Dim from_cmd As OleDbCommand = New OleDbCommand("select * from lan where engine=" & global_engine & " order by from_default desc,sorts asc", conn)
            Dim da_from = New OleDbDataAdapter
            da_from.SelectCommand = from_cmd
            da_from.Fill(dt_from)
            '目标语种
            Dim to_cmd As OleDbCommand = New OleDbCommand("select * from lan where engine=" & global_engine & " order by to_default desc,sorts asc", conn)
            Dim da_to = New OleDbDataAdapter
            da_to.SelectCommand = to_cmd
            da_to.Fill(dt_to)

            select_from.DataSource = dt_from
            select_from.DisplayMember = "show_name"
            select_from.ValueMember = "code"

            select_to.DataSource = dt_to
            select_to.DisplayMember = "show_name"
            select_to.ValueMember = "code"
            '初始化
            Dim ini_engine = ini_obj.GetINIW("setting", "engine", "0", ini_file)
            Dim ini_from = ini_obj.GetINIW("setting", "from_code", "", ini_file)
            Dim ini_to = ini_obj.GetINIW("setting", "to_code", "", ini_file)
            If global_engine = ini_engine And (ini_from <> "" Or ini_to <> "") Then
                For Each item As DataRowView In dt_from.DefaultView
                    Dim row As DataRow = item.Row
                    Dim code As String = row("code")
                    If code = Trim(ini_from) Then
                        select_from.SelectedItem = item
                    End If
                Next
                select_to.SelectedValue = Trim(ini_to)
            Else
                ini_obj.WriteINIW("setting", "from_code", select_from.SelectedValue, ini_file)
                ini_obj.writeINIW("setting", "to_code", select_to.SelectedValue, ini_file)
            End If

            '左侧label
            Label1.Text = select_from.GetItemText(select_from.Items(select_from.SelectedIndex))
            Label2.Text = select_to.GetItemText(select_to.Items(select_to.SelectedIndex))
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Private Function GetRoundedRectPath(ByVal Rectangle As Rectangle, ByVal r As Integer) As GraphicsPath

        Rectangle.Offset(-1, -1)
        Dim RoundRect As New Rectangle(Rectangle.Location, New Size(r - 1, r - 1))
        Dim path As New System.Drawing.Drawing2D.GraphicsPath
        path.AddArc(RoundRect, 180, 90) '左上角

        RoundRect.X = Rectangle.Right - r '右上角
        path.AddArc(RoundRect, 270, 90)

        RoundRect.Y = Rectangle.Bottom - r '右下角
        path.AddArc(RoundRect, 0, 90)
        RoundRect.X = Rectangle.Left '左下角
        path.AddArc(RoundRect, 90, 90)

        path.CloseFigure()
        Return path
    End Function

    Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
        Me.Close()
        End
    End Sub

    Private Sub source_from_TextChanged(sender As Object, e As EventArgs) Handles source_from.TextChanged
        Dim f As String = select_from.SelectedValue.ToString
        Dim t As String = select_to.SelectedValue.ToString
        If f = t Or t = "" Or Trim(source_from.Text) = "" Then
            source_to.Text = source_from.Text '源语种与目标语种一直
            Exit Sub
        End If
        Dim factory = New Lanfactory(global_engine)
        Dim from_text = StringAsUtf8Bytes(source_from.Text)
        'from_text = strChar(from_text)
        If singleModel = False Then
            source_to.Text = factory.trans(from_text, f, t)
        Else
            showMiniForm(factory.trans(from_text, f, t))
        End If
    End Sub
    '转换utf8编码
    Private Function StringAsUtf8Bytes(ByVal str As String) As String
        Dim utf8, gbk As System.Text.Encoding
        utf8 = System.Text.Encoding.GetEncoding("utf-8")
        gbk = System.Text.Encoding.GetEncoding("gbk")
        Dim bytes() As Byte = gbk.GetBytes(str)
        bytes = System.Text.Encoding.Convert(gbk, utf8, bytes)
        Return utf8.GetString(bytes)
    End Function
    '去除不必要的字符
    Public Function strChar(ByVal Str As String) As String
        Dim ReStr As String = Str
        If Not ((Str = "") OrElse (Str Is Nothing)) Then
            If (Str.Length > 0) Then
                ReStr = Str.Replace("" & vbLf, "").Replace("" & vbTab, "").Replace("" & vbCr, "")
            End If
        End If
        Return ReStr
    End Function


    ' Caption bar height;
    Protected Overrides Sub WndProc(ByRef m As Message)
        If m.Msg = &H84 And no_remove = False Then
            ' Trap WM_NCHITTEST
            Dim pos As New Point(m.LParam.ToInt32() And &HFFFF, m.LParam.ToInt32() >> 16)
            pos = Me.PointToClient(pos)
            If pos.Y < cCaption Then
                m.Result = IntPtr.op_Explicit(2)
                ' HTCAPTION
                Return
            End If
            If pos.X >= Me.ClientSize.Width - cGrip AndAlso pos.Y >= Me.ClientSize.Height - cGrip Then
                m.Result = IntPtr.op_Explicit(17)
                ' HTBOTTOMRIGHT
                Return
            End If
        End If
        MyBase.WndProc(m)
    End Sub

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        System.Diagnostics.Process.Start("https://www.damicms.com/public/juan")
    End Sub

    Private Sub PictureBox3_Click(sender As Object, e As EventArgs) Handles PictureBox3.Click
        If no_remove = False Then
            no_remove = True
            PictureBox3.Image = Image.FromFile(app_path & "\gu.png")
        Else
            no_remove = False
            PictureBox3.Image = Image.FromFile(app_path & "\nogu.png")
        End If
    End Sub

    Private Sub select_from_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles select_from.SelectionChangeCommitted
        ini_obj.WriteINIW("setting", "from_code", Trim(select_from.SelectedValue), ini_file)
        Label1.Text = select_from.GetItemText(select_from.SelectedItem)
    End Sub

    Private Sub select_to_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles select_to.SelectionChangeCommitted
        ini_obj.WriteINIW("setting", "to_code", Trim(select_to.SelectedValue), ini_file)
        Label2.Text = select_to.GetItemText(select_to.SelectedItem)
    End Sub

    Private Sub PictureBox4_Click(sender As Object, e As EventArgs) Handles PictureBox4.Click
        singleModel = True
        showMiniForm(source_to.Text)
    End Sub

    Private Sub showMiniForm(ByVal word As String)
        Me.Hide()
        m2.ShowLrc(word, 1.0)
        m2.show
    End Sub

    Private Sub PictureBox5_Click(sender As Object, e As EventArgs) Handles PictureBox5.Click
        If stopHook = False Then
            stopHook = True
            PictureBox5.Image = Image.FromFile(app_path & "\play.png")
            hookHandle.MouseHookEnabled = False
        Else
            stopHook = False
            PictureBox5.Image = Image.FromFile(app_path & "\stop.png")
            hookHandle.MouseHookEnabled = True
        End If
    End Sub

    Private Sub PictureBox6_Click(sender As Object, e As EventArgs) Handles PictureBox6.Click
        'Me.ShowInTaskbar = False
        NotifyIcon1.Visible = True
        Me.Hide()
    End Sub

    Private Sub NotifyIcon1_Click(sender As Object, e As EventArgs) Handles NotifyIcon1.Click
        'Me.ShowInTaskbar = True
        NotifyIcon1.Visible = False
        Me.Show()
    End Sub

    Private Sub select_from_SelectedIndexChanged(sender As Object, e As EventArgs) Handles select_from.SelectedIndexChanged

    End Sub
End Class
